package org.kust.bbs.admin.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.kust.bbs.admin.mapper.PermissionMapper;
import org.kust.bbs.admin.mapper.RolePermissionMapper;
import org.kust.bbs.admin.service.IPermissionService;
import org.kust.bbs.common.ex.ServiceException;
import org.kust.bbs.common.web.JsonPage;
import org.kust.bbs.common.web.State;
import org.kust.bbs.pojo.dto.PermissionAddDTO;
import org.kust.bbs.pojo.dto.PermissionUpdateDTO;
import org.kust.bbs.pojo.entity.Permission;
import org.kust.bbs.pojo.vo.PageQuery;
import org.kust.bbs.pojo.vo.PermissionVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 权限表 服务实现类
 * </p>
 */
@Service
public class PermissionServiceImpl implements IPermissionService {
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Override
    public void addPermission(PermissionAddDTO permissionAddDTO) {
        //转化对象
        Permission permission = new Permission();
        BeanUtils.copyProperties(permissionAddDTO, permission);
        permissionMapper.insertPermission(permission);
    }

    @Override
    public JsonPage<PermissionVO> listPermissions(PageQuery pageQuery) {
        PageHelper.startPage(pageQuery.getPageNum(), pageQuery.getSizeNum());
        List<PermissionVO> permissionVOList = permissionMapper.selectPermissions();
        PageInfo pageInfo = new PageInfo(permissionVOList);
        return JsonPage.restPage(pageInfo);
    }

    @Override
    public void updatePermission(PermissionUpdateDTO permissionUpdateDTO) {
        Permission permission = new Permission();
        BeanUtils.copyProperties(permissionUpdateDTO, permission);
        permissionMapper.updatePermission(permission);
    }

    @Override
    public void deletePermission(Long id) {
        //检查是否有关联
        int count = rolePermissionMapper.selectExistByPermissionId(id);
        if (count != 0) {
            throw new ServiceException(State.ERR_UPDATE, "当前权限有关联角色不可删除");
        }
        permissionMapper.deletePermission(id);
    }
}
